package com.mj.factory.kanBan;

import org.apache.commons.collections4.map.HashedMap;
import org.apache.log4j.Logger;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * author : cRyann
 *
 * @create 2017-09-30
 **/
@RestController
@RequestMapping("kanBan")
//@Controller
public class KanBanController {
    private Logger logger = Logger.getLogger(this.getClass());

    @Autowired
    @PersistenceContext
    private EntityManager em;

    @Autowired
    private SimpMessagingTemplate template;


    public void sendDeviceColor(Object obj) {
//        logger.info("Send wsSocket.../topicKanBan/deviceData");
        template.convertAndSend("/topicKanBan/deviceData", obj);
    }


    public void sendChartsData(String technologyName) {
//        logger.info("Send webSocket[chartData]");
        template.convertAndSend("/topicKanBan/chartsData", getChartData(technologyName));
    }

    public void sendWorkOrderData() {
//        logger.info("Send webSocket[tableData]");
        template.convertAndSend("/topicKanBan/tableData", getWorkOrders());
    }

    @MessageMapping("/getColor")//1
//    @SendTo("/topicKanBan/getMechanicsAllColor")//2
    public void sendMechanicsAllColor(Object object) {
        template.convertAndSend("/topicKanBan/getMechanicsAllColor", getMechanicsAllColor());
    }
    @MessageMapping("/getWorkOrders")//1
//    @SendTo("/topicKanBan/getMechanicsAllColor")//2
    public void sendWorkOrders(Object object) {
        template.convertAndSend("/topicKanBan/getWorkOrders", getWorkOrders());
    }


    @RequestMapping(value = "workOrders", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object getWorkOrders() {
        int a=0;
        Map<String, Object> map = new HashMap<>();
        String sql = "SELECT "
                + "	part_name, "
                + "	chart_number, "
                + "	task.NAME_, "
                + "	DATE_FORMAT(procinst.START_TIME_,'%Y-%m-%d %H:%i:%S') as START_TIME_ , "
                + "	work_order_status "
                + "FROM "
                + "	mj_work_order wo, "
                + "	act_ru_task task, "
                + "	act_hi_procinst procinst "
                + "WHERE "
                + "	locate(		wo.chart_number,		task.PROC_DEF_ID_	) > 0 "
                + "AND procinst.PROC_DEF_ID_ = task.PROC_DEF_ID_ "
                + "AND ISNULL(procinst.END_TIME_)";
        Query query = em.createNativeQuery(sql);
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List list = query.getResultList();
        map.put("rows", list);
        return map;
    }

    @RequestMapping(value = "queryAllColor", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object getMechanicsAllColor() {
        Map<String, Object> map = new HashedMap();
        int length;
        String sql = "SELECT * FROM sys_mechanics";
        Query query = em.createNativeQuery(sql);
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List list = query.getResultList();
        length = list.size();
        map.put("length", length);
        map.put("items", list);
        return map;
    }

    public Object getChartData(String technologyName) {
        Map<String, Object> map = new HashedMap();
        if (technologyName != null) {
            String sql = "SELECT ROUND("
                    + " (SELECT SUM(DURATION_)/3600/1000 FROM act_hi_taskinst WHERE NAME_ = '"
                    + technologyName
                    + "') "
                    + " /(SELECT SUM(estimate_time) SUM FROM mj_process_flow WHERE production_processes = '"
                    + technologyName
                    + "')*100 ,2) AS result"
                    + " FROM DUAL ";
            Query query = em.createNativeQuery(sql);
            query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
            List list = query.getResultList();
            Map m = (Map) list.get(0);
            map.put("technologyName", technologyName);
            map.put("result", String.valueOf(m.get("result")));
        } else {
            map.put("technologyName", null);
        }
        String sql = "SELECT  " +
                " ROUND(Completed/maxCnt,2)*100 as completeRate, " +
                " maxCnt, " +
                " maxCnt-Not_Ready-Completed as planCnt, " +
                " Running+Stop as actualCnt FROM ( " +
                " SELECT " +
                " SUM(IF (work_order_status = 'Not_Ready',1,0)) AS Not_Ready , " +
                " SUM(IF (work_order_status = 'Running',1,0)) AS Running, " +
                " SUM(IF (work_order_status = 'Stop',1,0)) AS Stop, " +
                " SUM(IF (work_order_status = 'Completed',1,0)) AS Completed, " +
                " SUM(IF (work_order_status = 'Ready',1,0)) AS Ready, " +
                " COUNT(*) AS maxCnt " +
                "FROM " +
                " mj_work_order) a ";
        Query query = em.createNativeQuery(sql);
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List list = query.getResultList();
        Map m2 = (Map) list.get(0);
        map.put("maxCnt", String.valueOf(m2.get("maxCnt")));
        map.put("planCnt", String.valueOf(m2.get("planCnt")));
        map.put("completeRate", String.valueOf(m2.get("completeRate")));
        map.put("actualCnt", String.valueOf(m2.get("actualCnt")));
        return map;
    }
}
